﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="DataCapture.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using GenericTools;
using System.Drawing;
using DataModels.Common;
using DataModels.Enumerations;
using ReportingManagement.Components;
using GenericTools.Models;
using DataModels.Models.OfflineData;
using GenericTools.OfflineDataCapture;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        #region Constants
        private const int DATA_CAPTURE_FACILITY_CODE_ROW_INDEX = 0;
        private const int DATA_CAPTURE_MONTH_ROW_INDEX = 1;
        private const int DATA_CAPTURE_YEAR_ROW_INDEX = 2;
        private const int DATA_CAPTURE_FIRST_INDICATOR_ROW_INDEX = 3;

        private const string DATA_CAPTURE_SHORT_CODE_COLUMN_NAME = "ShortCode";
        private const string DATA_CAPTURE_DESCRIPTION_COLUMN_NAME = "DataDescription";
        private const string DATA_CAPTURE_DATA_COLUMN_NAME = "Data";
        #endregion

        private bool tabPageDataCaptureLoaded = false;

        private void tabPageDataCapture_Enter(object sender, EventArgs e)
        {
            if (!tabPageDataCaptureLoaded)
            {
                if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                    (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                {
                    bool offlineDataCapturingInitialized = OfflineDataCapturing.InitializeOfflineDataSavingEnvironment();
                    if (offlineDataCapturingInitialized) btnDCSave.Text = "Upload when Connected";
                    else
                    {
                        cbDIRepType.Enabled = false;
                        cboRegionsForData.Enabled = false;
                        cboDistrictsForData.Enabled = false;
                        cbDCFacCode.Enabled = false;
                        dgvDIRepDetails.Enabled = false;
                        btnDataCaptureReset.Enabled = false;
                        btnDCSave.Enabled = false;
                        label5.Visible = false;
                        lblReportError.Text = "Click on Import Report Data from File... to verify report input file.";
                        lblReportError.ForeColor = Color.Blue;
                        tabPageDataCaptureLoaded = true;
                        return;
                    }
                }

                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable dataTable = Utilities.GetAllExpectedReportViews();
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cbDIRepType.Items.Clear();
                    foreach (DataRow row in dataTable.Rows)
                    {
                        ListItem item = new ListItem();
                        item.Text = row["ReportName"].ToString();
                        item.Value = row["RepID"];
                        cbDIRepType.Items.Add(item);                        
                    }
                    try
                    {
                        cbDIRepType.SelectedIndex = 0;
                    }
                    catch { }

                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.FACILITY:
                            btnImportData.Enabled = false;
                            string facilityCode = this.authenticatedUser.AccessLevelValue;
                            dataTable = Utilities.GetFacilityRegion(facilityCode);
                            //dataTable = Utilities.GetFacilityDetails(facilityCode);
                            break;

                        case AccessLevel.DISTRICT:
                            int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetDistrictRegion(districtID);
                            //dataTable = Utilities.GetFacilitiesDetailsByDistrict(districtID);
                            break;

                        case AccessLevel.REGION:
                            int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetRegion(regionID);
                            //dataTable = Utilities.GetFacilitiesDetailsByRegion(regionID);
                            break;

                        case AccessLevel.NATION:
                            dataTable = Utilities.GetAllRegions(this.authenticatedUser.SupportingPartnerId);
                            break;

                        case AccessLevel.ADMINISTRATOR:
                            btnImportData.Enabled = true;
                            //dataTable = Utilities.GetAllFacilities();
                            dataTable = Utilities.GetAllRegions();
                            break;
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cboRegionsForData.ValueMember = "RegionID";
                    cboRegionsForData.DisplayMember = "RegionName";
                    cboRegionsForData.DataSource = dataTable;
                    
                    PopulateReportDataPositionDetails();
                    // Disabling column header sorting
                    foreach (DataGridViewColumn column in dgvDIRepDetails.Columns) column.SortMode = DataGridViewColumnSortMode.NotSortable;

                    tabPageDataCaptureLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void cbDIRepType_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateReportDataPositionDetails();

            // This will clear the all data elements except the facility code
            for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
            {
                dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = String.Empty;
            }
            lblReportError.Text = String.Empty;
        }

        private void cboRegionsForData_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dataTable = null;
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.FACILITY:
                    string facilityCode = this.authenticatedUser.AccessLevelValue;
                    dataTable = Utilities.GetFacilityDistrict(facilityCode);
                    break;

                case AccessLevel.DISTRICT:
                    int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                    dataTable = Utilities.GetDistrict(districtID);
                    break;

                case AccessLevel.REGION:
                case AccessLevel.NATION:
                    int regionID = Int32.Parse(cboRegionsForData.SelectedValue.ToString());
                    dataTable = Utilities.GetDistrictsByRegion(regionID, this.authenticatedUser.SupportingPartnerId);
                    break;

                case AccessLevel.ADMINISTRATOR:
                    int r = Int32.Parse(cboRegionsForData.SelectedValue.ToString());
                    dataTable = Utilities.GetDistrictsByRegion(r);
                    break;
            }
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboDistrictsForData.ValueMember = "DistrictNo";
            cboDistrictsForData.DisplayMember = "District";
            cboDistrictsForData.DataSource = dataTable;
        }

        private void cboDistrictsForData_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dataTable = null;
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            switch (this.authenticatedUser.Level)
            {
                case AccessLevel.FACILITY:
                    string facilityCode = this.authenticatedUser.AccessLevelValue;
                    dataTable = Utilities.GetFacilityDetails(facilityCode);
                    break;

                case AccessLevel.DISTRICT:
                    int districtID = Int32.Parse(cboDistrictsForData.SelectedValue.ToString());
                    dataTable = Utilities.GetFacilitiesDetailsByDistrict(districtID);
                    break;

                case AccessLevel.REGION:
                case AccessLevel.NATION:
                    int ID = Int32.Parse(cboDistrictsForData.SelectedValue.ToString());
                    dataTable = Utilities.GetFacilitiesDetailsByDistrict(ID, this.authenticatedUser.SupportingPartnerId);
                    break;

                case AccessLevel.ADMINISTRATOR:
                    int D = Int32.Parse(cboDistrictsForData.SelectedValue.ToString());
                    dataTable = Utilities.GetFacilitiesDetailsByDistrict(D);
                    break;
            }
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cbDCFacCode.ValueMember = "FacCode";
            cbDCFacCode.DisplayMember = "FacName";
            cbDCFacCode.DataSource = dataTable;
        }

        private void cbDCFacCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            //PopulateReportDataPositionDetails();
            try
            {
                dgvDIRepDetails.Rows[0].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = cbDCFacCode.SelectedValue;
                for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
                {
                    dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = String.Empty;
                }
                lblReportError.Text = String.Empty;
                txtComment.Clear();
            }
            catch { }
        }

        private void btnDataCaptureReset_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
            {
                dgvDIRepDetails.Rows[i].Cells["Data"].Value = String.Empty;
            }
            txtComment.Clear();
        }

        private void PopulateReportDataPositionDetails()
        {
            try
            {
                ListItem item = (ListItem)cbDIRepType.SelectedItem;
                int reportID = Int32.Parse(item.Value.ToString());
                DataTable reportDataDescription = null;
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    reportDataDescription = Utilities.GetReportAllDataDescriptions(reportID);
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                    return;
                }

                if (!reportDataDescription.Columns.Contains(DATA_CAPTURE_DATA_COLUMN_NAME)) reportDataDescription.Columns.Add(DATA_CAPTURE_DATA_COLUMN_NAME);
                dgvDIRepDetails.DataSource = reportDataDescription;
                dgvDIRepDetails.Columns["DataType"].Visible = false;
                dgvDIRepDetails.Columns["DataPosition"].Visible = false;
                //dgvDIRepDetails.Columns["DataDescription"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                dgvDIRepDetails.Columns[DATA_CAPTURE_SHORT_CODE_COLUMN_NAME].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDIRepDetails.Columns[DATA_CAPTURE_SHORT_CODE_COLUMN_NAME].ReadOnly = true;

                dgvDIRepDetails.Columns[DATA_CAPTURE_DESCRIPTION_COLUMN_NAME].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                dgvDIRepDetails.Columns[DATA_CAPTURE_DESCRIPTION_COLUMN_NAME].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvDIRepDetails.Columns[DATA_CAPTURE_DESCRIPTION_COLUMN_NAME].ReadOnly = true;

                dgvDIRepDetails.Columns[DATA_CAPTURE_DATA_COLUMN_NAME].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dgvDIRepDetails.Rows[0].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = cbDCFacCode.SelectedValue;
                dgvDIRepDetails.Rows[0].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].ReadOnly = true;
            }
            catch { }
        }

        private void btnDCSave_Click(object sender, EventArgs e)
        {
            int count = dgvDIRepDetails.Rows.Count;
            ListItem item = (ListItem)cbDIRepType.SelectedItem;
            int reportID = Int32.Parse(item.Value.ToString());
            string reportName = item.Text;
            string facilityName = ((DataRowView)(cbDCFacCode.SelectedItem))["FacName"].ToString();

            #region Looking for empty and non-integer values
            for (int i = 1; i < count; i++)
            {
                string value = String.Empty;
                try
                {
                    value = dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();
                    Int32.Parse(value);
                }
                catch
                {
                    dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Selected = true;
                    string message = String.Format("Please provide valid number at row {0}", (i+1));
                    MessageBox.Show(this, message, AppConfiguration.ApplicationName, 
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    lblReportError.Text = message;
                    lblReportError.ForeColor = Color.Red;
                    return;
                }
            }
            #endregion

            #region Going through business rules
            Cursor.Current = Cursors.WaitCursor;
            btnDCSave.Enabled = false;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable reportDataLocation = Utilities.GetReportAllDataDescriptions(reportID);
            DataTable reportRules = Utilities.GetReportRules(reportID);

            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            int rulesCount = reportRules.Rows.Count;
            for (int i = 0; i < rulesCount; i++)
            {
                DataRow row = reportRules.Rows[i];
                int measurePosNo = int.Parse(row["MeasurePosNo"].ToString());
                string comparedToOrderPos = row["ComparedToOrderPos"].ToString();
                bool multicomparison = bool.Parse(row["Multicomparison"].ToString());
                string comparisonSign = row["ComparisonSign"].ToString();

                int value1 = 0;
                int value2 = 0;
                bool okToContinue = false;
                
                if (multicomparison)
                {
                    #region Dealing with Multicomparison
                    ArithmeticOperation operation = ArithmeticOperation.ADD;
                    //value1 = data[measurePosNo - offset];
                    value1 = int.Parse(dgvDIRepDetails.Rows[measurePosNo - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString());
                    StringBuilder sBuilder2 = new StringBuilder();
                    sBuilder2.Append("(");
                    string[] parts = comparedToOrderPos.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string part in parts)
                    {
                        try
                        {
                            int position = int.Parse(part);
                            //int value = data[position - offset];
                            int value = int.Parse(dgvDIRepDetails.Rows[position - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString());
                            string shortCode = reportDataLocation.Rows[position - 1]["ShortCode"].ToString();
                            sBuilder2.Append(shortCode);
                            switch (operation)
                            {
                                case ArithmeticOperation.ADD:
                                    value2 += value;
                                    break;

                                case ArithmeticOperation.SUBTRACT:
                                    value2 -= value;
                                    break;

                                case ArithmeticOperation.MULTIPLY:
                                    value2 *= value;
                                    break;

                                case ArithmeticOperation.DIVIDE:
                                    value2 /= value;
                                    break;
                            }
                        }
                        catch
                        {
                            switch (part)
                            {
                                case "+":
                                    operation = ArithmeticOperation.ADD;
                                    sBuilder2.Append("+");
                                    break;

                                case "-":
                                    operation = ArithmeticOperation.SUBTRACT;
                                    sBuilder2.Append("-");
                                    break;

                                case "*":
                                    operation = ArithmeticOperation.MULTIPLY;
                                    sBuilder2.Append("*");
                                    break;

                                case "/":
                                    operation = ArithmeticOperation.DIVIDE;
                                    sBuilder2.Append("/");
                                    break;
                            }
                        }
                    }
                    sBuilder2.Append(")");
                    bool okToContinue2 = Utilities.Compare(value1, comparisonSign, value2);
                    if (!okToContinue2)
                    {
                        string sValue1 = reportDataLocation.Rows[measurePosNo - 1]["ShortCode"].ToString();
                        string sValue2 = sBuilder2.ToString();
                        string senderNum = String.Format("{0} [{1} Level]", this.authenticatedUser.FullName, this.authenticatedUser.AccessLevelText);
                        string msg = Utilities.GetTranslationText(senderNum, GenericTools.ReportProcessing.ReportProcessor.COMPARISON_LABEL);
                        string errorReply = String.Format(msg, sValue1, comparisonSign, sValue2);
                        
                        //E.g. ANC Jan 2013: Kosa kwenye taarifa...                        
                        MessageBox.Show(this, errorReply, AppConfiguration.ApplicationName,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        lblReportError.Text = errorReply;
                        lblReportError.ForeColor = Color.Red;
                        dgvDIRepDetails.Rows[measurePosNo - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Selected = true;
                        btnDCSave.Enabled = true;
                        return;
                    }
                    #endregion
                }
                else
                {
                    #region Dealing with Simple Comparison
                    int comparePosNo = 0;
                    bool value2IsScalar = false;
                    value1 = Int32.Parse(dgvDIRepDetails.Rows[measurePosNo - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString());
                    if (comparedToOrderPos.Contains("["))
                    {
                        value2IsScalar = true;
                        value2 = Int32.Parse(comparedToOrderPos.Substring(1, comparedToOrderPos.Length - 2));
                    }
                    else
                    {
                        comparePosNo = Int32.Parse(comparedToOrderPos);
                        value2 = Int32.Parse(dgvDIRepDetails.Rows[comparePosNo - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString());
                        comparePosNo = int.Parse(comparedToOrderPos);
                    }                   
                    
                    okToContinue = Utilities.Compare(value1, comparisonSign, value2);
                    if (!okToContinue)
                    {
                        string sValue1 = dgvDIRepDetails.Rows[measurePosNo - 1].Cells[DATA_CAPTURE_SHORT_CODE_COLUMN_NAME].Value.ToString();
                        string sValue2 = String.Empty;
                        if (value2IsScalar) sValue2 = value2.ToString();
                        else sValue2 = dgvDIRepDetails.Rows[comparePosNo - 1].Cells[DATA_CAPTURE_SHORT_CODE_COLUMN_NAME].Value.ToString();
                        
                        string message = String.Format("{0} must be {1} {2}", sValue1, comparisonSign, sValue2);
                        MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        lblReportError.Text = message;
                        lblReportError.ForeColor = Color.Red;
                        dgvDIRepDetails.Rows[measurePosNo - 1].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Selected = true;
                        btnDCSave.Enabled = true;
                        return;
                    }
                    #endregion
                }
            }
            #endregion

            #region Building up SMS-based report for sending the report
            StringBuilder sBuilder = new StringBuilder();            
            string reportCode = String.Empty;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                DataTable dataTable = Utilities.GetReportDetails(reportID);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";

                DataRow row = dataTable.Rows[0];
                reportCode = row["RepVersion"].ToString();
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
                btnDCSave.Enabled = true;
                return;
            }

            string facilityCode = dgvDIRepDetails.Rows[DATA_CAPTURE_FACILITY_CODE_ROW_INDEX].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();
            string month = dgvDIRepDetails.Rows[DATA_CAPTURE_MONTH_ROW_INDEX].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();
            string year = dgvDIRepDetails.Rows[DATA_CAPTURE_YEAR_ROW_INDEX].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();

            sBuilder.Append(reportCode);
            sBuilder.Append(".");
            sBuilder.Append(facilityCode);
            sBuilder.Append(",");
            sBuilder.Append(month);
            sBuilder.Append(",");
            sBuilder.Append(year);

            for (int i = DATA_CAPTURE_FIRST_INDICATOR_ROW_INDEX; i < count; i++)
            {
                DataGridViewRow row = dgvDIRepDetails.Rows[i];
                string data = row.Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();
                sBuilder.Append(",");
                sBuilder.Append(data);
            }
            #endregion

            string reportingText = sBuilder.ToString();
            string errorText = String.Empty;

            #region Sending the report to the server
            try
            {
                string senderNum = String.Format("{0} [{1} Level]",
                    this.authenticatedUser.FullName, this.authenticatedUser.AccessLevelText);
                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                string comments = string.IsNullOrWhiteSpace(txtComment.Text) ? null : txtComment.Text;

                if (((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                    (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
                    && OfflineDataCapturing.InitializeOfflineDataSavingEnvironment())
                {
                    #region Saving the data locally, uploading will be done later
                    List<OfflineReportIndicator> reportIndicators = new List<OfflineReportIndicator>();
                    foreach (DataGridViewRow r in dgvDIRepDetails.Rows)
                    {
                        string shortCode = r.Cells[DATA_CAPTURE_SHORT_CODE_COLUMN_NAME].Value.ToString();
                        string description = r.Cells[DATA_CAPTURE_DESCRIPTION_COLUMN_NAME].Value.ToString();
                        string value = r.Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value.ToString();

                        var indicator = new OfflineReportIndicator
                        {
                            ShortCode = shortCode,
                            Name = description,
                            Value = value
                        };
                        reportIndicators.Add(indicator);
                    }

                    OfflineReport offlineReport = new OfflineReport
                    {
                        FacilityCode = facilityCode,
                        FacilityName = facilityName,
                        ReportYear = int.Parse(year),
                        ReportMonth = int.Parse(month),
                        CreatedByUserId = this.authenticatedUser.ID,
                        CreatedByUserName = this.authenticatedUser.FullName,
                        DateSavedOffline = DateTime.Now,
                        ReportComments = comments,
                        ReportId = reportID,
                        ReportName = reportName,
                        ReportMessage = reportingText,
                        Indicators = reportIndicators
                    };

                    bool added = OfflineDataCapturing.AddOfflineReport(offlineReport, false);
                    if (!added)
                    {
                        string message = "It seems there is an offline report of similar data that was saved earlier but "
                            + "not upload to the server. If you add another one previous data will be overwritten."
                            + Environment.NewLine + Environment.NewLine
                            + "Do you want to overwrite existing data?";
                        DialogResult response = MessageBox.Show(this, message, AppConfiguration.ApplicationName, 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (response == DialogResult.No) return;
                        else added = OfflineDataCapturing.AddOfflineReport(offlineReport, true);
                        
                        // Now complete failure of adding offline report but no exception send out, weird hah!?
                        if (!added)
                        {
                            MessageBox.Show(this, "Unknown error occured that prevented the offline report from being saved",
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }

                    // Now from this point on, we must proceed with what we have
                    if (added)
                    {
                        bool saved = OfflineDataCapturing.SaveOfflineData();
                        if (saved)
                        {
                            MessageBox.Show(this,
                                "Your report has been saved and it will be uploaded to the server once the connection is detected",
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // Now clear the form to avoid repetition
                            for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
                            {
                                dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = String.Empty;
                            }
                            return;
                        }
                        else
                        {
                            MessageBox.Show(this,
                                "Your report has not been saved. There is an unknown that prevents this operation.",
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }                        
                    }
                    #endregion
                }
                else
                {
                    #region Save data data directly to the server
                    ReportingMessage reportingMessage = Utilities.SendReport(senderNum, reportingText/*, authenticatedUser.UserSignature*/, false, comments);
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    if (reportingMessage.Status == ReportingError.NO_ERROR_LABEL)
                    {
                        lblReportError.Text = reportingMessage.Message;
                        lblReportError.ForeColor = Color.Blue;
                        MessageBox.Show(this, reportingMessage.Message, AppConfiguration.ApplicationName,
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnDCSave.Enabled = true;
                        for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
                        {
                            dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = String.Empty;
                        }
                        return;
                    }
                    else // Validation failed
                    {
                        #region First attempt failed, Could be validation or existing report
                        if (reportingMessage.Status == ReportingError.REPORT_ALREADY_SUBMITTED_LABEL)
                        {
                            DialogResult response = MessageBox.Show(this,
                                "Report is already submitted.\nDo you want to re-submit the report?",
                                AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (response == System.Windows.Forms.DialogResult.Yes)
                            {
                                sBuilder = new StringBuilder();
                                sBuilder.Append(reportingText);
                                sBuilder.Append(",");
                                sBuilder.Append("RESUBMIT");
                                reportingText = sBuilder.ToString();

                                Cursor.Current = Cursors.WaitCursor;
                                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                                reportingMessage = Utilities.SendReport(senderNum, reportingText/*, authenticatedUser.UserSignature*/, false, comments);
                                Cursor.Current = Cursors.Default;
                                toolStripStatusLabel.Text = "Ready";

                                if (reportingMessage.Status == ReportingError.NO_ERROR_LABEL)
                                {
                                    lblReportError.Text = reportingMessage.Message;
                                    lblReportError.ForeColor = Color.Blue;
                                    MessageBox.Show(this, reportingMessage.Message, AppConfiguration.ApplicationName,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    for (int i = 1; i < dgvDIRepDetails.Rows.Count; i++)
                                    {
                                        dgvDIRepDetails.Rows[i].Cells[DATA_CAPTURE_DATA_COLUMN_NAME].Value = String.Empty;
                                    }
                                    txtComment.Clear();
                                }
                                else
                                {
                                    lblReportError.Text = reportingMessage.Message;
                                    lblReportError.ForeColor = Color.Red;
                                    MessageBox.Show(this, reportingMessage.Message, AppConfiguration.ApplicationName,
                                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    btnDCSave.Enabled = true;
                                    return;
                                }
                            }
                        }
                        else // other errors beside repetition
                        {
                            lblReportError.Text = reportingMessage.Message;
                            lblReportError.ForeColor = Color.Red;
                            MessageBox.Show(this, reportingMessage.Message, AppConfiguration.ApplicationName,
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        #endregion
                    }
                    #endregion
                }
                btnDCSave.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
                btnDCSave.Enabled = true;
                return;
            }
            finally
            {
                btnDCSave.Enabled = true;
            }
            #endregion
        }

        private void btnReportSizeDataCapture_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            cbDIRepType.Enabled = false;
            btnReportSizeDataCapture.Enabled = false;
            DataTable dataTable = null;
            Application.DoEvents();

            if (btnReportSizeDataCapture.Text == "More...")
            {
                dataTable = Utilities.GetAllExpectedReports();
                btnReportSizeDataCapture.Text = "Less...";
            }
            else
            {
                dataTable = Utilities.GetAllExpectedReportViews();
                btnReportSizeDataCapture.Text = "More...";
            }

            cbDIRepType.Items.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row["ReportName"].ToString();
                item.Value = row["RepID"];
                cbDIRepType.Items.Add(item);
            }
            try
            {
                cbDIRepType.SelectedIndex = 0;
            }
            catch { }
            cbDIRepType.Enabled = true;
            btnReportSizeDataCapture.Enabled = true;
            toolStripStatusLabel.Text = "Ready";
            Cursor.Current = Cursors.Default;
        }

        private void btnImportData_Click(object sender, EventArgs e)
        {
            ImportReportData importReportData = new ImportReportData(authenticatedUser);
            importReportData.ShowDialog(this);
        }

        bool tabPageMTUHAANCFormLoaded = false;
        private void tabPageMTUHAANCForm_Enter(object sender, EventArgs e)
        {
            if (!tabPageMTUHAANCFormLoaded)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    var mtuhaTabs = elementHost2.Child as MTUHAReportsTab;
                    if (mtuhaTabs != null)
                    {
                        var ancForm = mtuhaTabs.FindName("ancForm") as ANCMTUHAReport;
                        var ldForm = mtuhaTabs.FindName("ldForm") as LDMTUHAReport;
                        if (ancForm != null)
                        {
                            ancForm.StatusChanged += ToolStripStatusLabel_StatusChanged;
                            ancForm.User = this.authenticatedUser;
                            ancForm.Mode = ANCMTUHAReport.ViewMode.EDITING;
                        }

                        if (ldForm != null)
                        {
                            ldForm.User = this.authenticatedUser;
                            ldForm.Mode = LDMTUHAReport.ViewMode.EDITING;
                        }
                    }
                    tabPageMTUHAANCFormLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }



    }
}
